<template>
    <div class="container">
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="120px" class="demo-ruleForm">
            <div v-if="active == 0">
                <el-row style=" padding: 20px;background: #fff;border: 1px solid #ddd;border-radius: 5px;">
                    <h3>生产信息</h3>
                    <el-col :span="12" >
                        <el-form-item label="品名：" @click.native="addManure">
                            <el-input placeholder="请输入内容" v-model="ruleForm.manageName"  style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="规格：" @click.native="addManure">
                            <el-input placeholder="请输入" v-model="ruleForm.specification" style="width: 300px">
					        <template slot="append">
					            <el-select
					                v-model="ruleForm.spec"
					                placeholder="单位"
									@click.native="addManure"
					                style="width:80px !important">
					                <el-option
					                    v-for="item in unitsList"
					                    :key="item.id"
					                    :label="item.name"
					                    :value="item.name"
					                ></el-option>
					            </el-select>
					        </template>
					    </el-input>
                        </el-form-item>
                        <el-form-item label="生产工艺：" >
                            <el-input placeholder="请输入内容" v-model="ruleForm.tename" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="执行标准：">
                            <el-input placeholder="请输入内容" v-model="ruleForm.tebz" style="width:300px"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="产品类型：" @click.native="addManure">
                            <el-input placeholder="请输入内容" v-model="ruleForm.type" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="预计产量：">
							<el-input placeholder="请输入" v-model="ruleForm.predictYield" style="width: 300px">
					        <template slot="append">
					            <el-select
					                v-model="ruleForm.monad"
					                placeholder="单位"
									@click.native="addManure"
					                style="width:80px !important">
					                <el-option
					                    v-for="item in unitsList"
					                    :key="item.id"
					                    :label="item.name"
					                    :value="item.name"
					                ></el-option>
					            </el-select>
					        </template>
					    </el-input>
                        </el-form-item>
                        <el-form-item label="批准文号：">
                            <el-input placeholder="请输入内容" v-model="ruleForm.tenum"  style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="标准：">
                            <!--<el-input placeholder="请输入内容" v-model="ruleForm.plantTime"  style="width:300px"></el-input>-->
                            <img :src="ruleForm.img" alt="" style="width:80px; height:80px; baorder:1px solid red">
                        </el-form-item>
                    </el-col>
                </el-row>
            </div>
			<div class="container" style="margin-top:20px;" v-if="active == 0">
				<h3>工艺工序</h3>
				<div style="height:500px;margin-top:20px;">
					<el-col :span ="7" style="height:500px;">
						<el-steps direction="vertical" :active="activeTechnologies">
							<el-step v-for ="(item,index) in technologies" :key="index" :title="item.processName" @click.native="switchTable(index)"></el-step>

						</el-steps>
					</el-col>
					 <el-col :span="14"  v-for="(item,index) in produceManageTechList" :key="index" v-if="switchTableIndex == index">
						  <el-form-item label="开始时间：" >
						      <el-date-picker
						          v-model="item.startTime"
						          type="date"
								  @change="gettime"
						          value-format="yyyy-MM-dd"
						          placeholder
						          style="width:300px"
						      ></el-date-picker>
						  </el-form-item>
						  <el-form-item label="结束时间：">
						      <el-date-picker
						          v-model="item.endTime"
						          type="date"
								  @change="gettime"
						          value-format="yyyy-MM-dd"
						          placeholder
						          style="width:300px"
						      ></el-date-picker>
						  </el-form-item>
						  <el-form-item label="视频监控：">
							  <el-select v-model="item.equipmentName" value-key="id" placeholder="请选择" @change="getfacilityDetails" style="width:300px">
							      <el-option
							        v-for="item in facilityList"
							        :key="item.id"
							        :label="item.name"
							        :value="item">
							      </el-option>
							    </el-select>
								<!-- <el-input placeholder="请输入内容"  v-model="technologyList[0].equipmentName" style="width:300px">
								</el-input> -->
						  </el-form-item>
						  <el-form-item label="负责人：">
								<!-- <el-input placeholder="请输入内容"  v-model="item.userName" style="width:300px">
								</el-input> -->
								<el-select  v-model="item.userName" @change="getuser" value-key="id" placeholder="请选择" style="width:300px">
									<el-option
							        v-for="item in user_findByAll"
							        :key="item.id"
							        :label="item.name"
							        :value="item">
							      </el-option>
								</el-select>
						  </el-form-item>
						  <el-form-item label="操作照片：">
							  <div @click="handelsuccess(index)">
							  	<el-upload
							      class="upload-poster"
							      action="https://jsonplaceholder.typicode.com/posts/"
							      :show-file-list="false"
							      :on-change="imgPreview"
							      :auto-upload="false">
							      <img v-if="item.operaImg" :src="item.operaImg" class="avatar">
							      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
							  </el-upload>
							  jpg、png、gif格式，60x60像素，不超过2MB
							  </div>
						  </el-form-item>

					  </el-col>
				</div>
			</div>
			<div class="conntainer" v-if="this.active == 1">
				<el-row class="container" style="margin-top:20px;">
					 <el-table
					:data="finishedProductList"
					border
					style="margin-top:20px;"
					ref="multipleTable"
					header-cell-class-name="table-header"
				>
					<el-table-column prop="productName" sortable label="品名">
						<template slot-scope="scope">
							{{scope.row.productName}}
							<!-- <el-select v-model="scope.row.productNames" @change="getname(scope.$index,scope.row.productNames)"  value-key="breedId"  filterable placeholder="请选择">
							    <el-option
							        v-for="item in tableData"
							        :key="item.breedId"
							        :label="item.breedName"
							        :value="item">

							    </el-option>
							</el-select> -->
						</template>
					</el-table-column>
					<el-table-column prop="batch" sortable label="生产批号">
						<template slot-scope="scope">
							<div>
							  <el-input placeholder="请输入内容"  v-model="scope.row.batch" >

							  </el-input>

							</div>
						</template>
					</el-table-column>
					<!-- <el-table-column prop="grade" sortable label="品级">
						<template slot-scope="scope">
							<el-select v-model="scope.row.grade"  value-key="name"  filterable placeholder="请选择">
							    <el-option
							        v-for="item in pj"
							        :key="item.name"
							        :label="item.name"
							        :value="item.name"
							    >
							    {{item.name}}
							    </el-option>
							</el-select>
						</template>
					</el-table-column> -->
					<el-table-column prop="totalNumber" sortable label="成品数量">
						<template slot-scope="scope">
							<div>
							  <el-input placeholder="请输入内容"  v-model="scope.row.totalNumber"  style="width:200px;">
									<template slot="append">
										{{scope.row.units}}
									</template>
							  </el-input>
							  <!-- <span style="margin-left:10px;">{{scope.row.units}}</span> -->
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="title" sortable label="关联产品介绍" >
						<template slot-scope="scope" >
							<div>
							  <el-input placeholder="请输入内容"  v-model="scope.row.title" @click.native="relevance(scope.$index, scope.row)" >

							  </el-input>
							</div>
						</template>
					</el-table-column>

					<el-table-column label="操作" width="150" align="center">
						<template slot-scope="scope">
							<el-button
								type="text"
								@click="handleCheck(scope.$index, scope.row)"
							>删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div @click="addProduct" class="addManure">添加成品</div>
			</el-row>
			</div>
			<el-form-item class="footerFixed" label-width="0px">
				<el-button @click="prev" v-if="active == 1 ">上一步</el-button>
                <el-button type="primary" @click="next" v-if="active == 0 ">下一步</el-button>
                <el-button v-if="active == 1" type="primary" @click="submitrule('ruleForm')">提交</el-button>
            </el-form-item>
            <!-- <el-form-item class="footerFixed" label-width="0px">
                <el-button type="success">取消</el-button>
                <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
            </el-form-item> -->
        </el-form>

		<!--     选择品名       -->
		<el-dialog title="选择品名" :visible.sync="dialogTableVisible">
		  	<el-table
		  		v-if="ifshow"
		        :data="materialList"
		        border
		        style="margin-top:20px;"
		        ref="multipleTable"
		        header-cell-class-name="table-header"
		    >
		        <el-table-column prop="tradeName" sortable label="品名"></el-table-column>
		        <!--<el-table-column v-if="source == '基地采收'" prop="soilName" sortable label="所属地块"></el-table-column>
				<el-table-column v-else prop="phone" sortable label="供应商"></el-table-column>  -->
		        <el-table-column prop="type" sortable label="产品类型"></el-table-column>
		        <el-table-column prop="materialSpecification" sortable label="规格">
					<template slot-scope="scope">
						{{scope.row.specification}}{{scope.row.spec}}
					</template>
				</el-table-column>
		        <el-table-column label="操作" width="150" align="center">
		            <template slot-scope="scope">
		                <el-button
		                    type="text"
		                    @click="handleSelect(scope.$index, scope.row)"
		                >选择</el-button>
		            </template>
		        </el-table-column>
		    </el-table>
			<el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" :current-page.sync="currentPage" :total="total"  @current-change="handleCurrentChange" style="margin-top:20px"></el-pagination>
		</el-dialog>
		<el-dialog title="选择产品介绍" :visible.sync="dialogTableVisible3">
			<el-table
			    :data="tableData3"
			    border
			    style="margin-top:20px;"
			    ref="multipleTable"
			    header-cell-class-name="table-header"
			>
				<el-table-column prop="img" sortable label="产品图">
					<template slot-scope="scope">
						<img :src="$store.state.imageUrls + scope.row.img" alt="" style="width:50px; height:50px;" v-if="scope.row.img != '' || scope.row.img!= null ">
					</template>
				</el-table-column>
			    <el-table-column prop="title" sortable label="产品标题"></el-table-column>
			    <!-- <el-table-column prop="createTime" sortable label="添加时间"></el-table-column> -->
			    <el-table-column prop="relatedProducts" sortable label="关联产品"></el-table-column>
				<el-table-column prop="quality" sortable label="保质期"></el-table-column>
			    <el-table-column label="操作" width="150" align="center">
			        <template slot-scope="scope">
			            <el-button
			                type="text"
			                @click="handleSelectProductDetails11(scope.$index, scope.row)"
			            >选择</el-button>

			        </template>
			    </el-table-column>
			</el-table>
			<el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" :current-page.sync="currentPage3"  @current-change="handleCurrentChange3" :total="total3" style="margin-top:20px"></el-pagination>

		</el-dialog>

		<!--      选择工艺工序           -->
		<el-dialog title="选择工艺工序" :visible.sync="dialogTableVisible1">
			<el-table
			    :data="tableData1"
			    border
			    style="margin-top:20px;"
			    ref="multipleTable"
			    header-cell-class-name="table-header"
			>
        <el-table-column prop="processName" sortable label="工艺名称"></el-table-column>
        <el-table-column prop="approvalNumber" sortable label="批准文号"></el-table-column>
				<el-table-column prop="standard" sortable label="执行标准"></el-table-column>
				<el-table-column prop="standardImg" sortable label="标准图">
					<template slot-scope="scope">
						<img :src="$store.state.pathimg + scope.row.standardImg" alt="" style="width:50px; height:50px;" v-if="scope.row.standardImg != '' || scope.row.standardImg!= null ">
					</template>
				</el-table-column>
			    <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
                <el-button
                    type="text"
                    @click="handleSelectProductDetails(scope.$index, scope.row)"
                >选择</el-button>
            </template>
			    </el-table-column>
			</el-table>
			<el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" :current-page.sync="currentPage1"  @current-change="handleCurrentChange1" :total="total1" style="margin-top:20px"></el-pagination>

		</el-dialog>
    </div>
</template>

<script>
	import { unit_findByList,user_findByAll,facility_findByAll,products_findByList} from "@/request/api"
	import {scTechnology_inquire,productionManagement_selectType,productionManagement_save,productionPlan_search,scTechnology_selectId} from "@/request/produceApi"
    export default {
        data(){
            return{
              rulefrom:{},
				activeTechnologies:0,
				technologies:[],
				ifshow:true,
				finishedProductList:[],
				dialogTableVisible1:false,
				materialList:[],
				reapName:'',
				soilName:'',
				processList:[],
				res:{
					images:[]
				},
				productName:'',
				headImg:{},
				tableData:[],
				source:"基地采收",
				dialogTableVisible:false,
                total:0,
                currentPage:1,
				currentPage1:1,
				total1:1,
				tableData1:[],
                pagesize:10,
                active:0,
                rules:{},
                ruleForm:{},
                labelPosition:"right",
				switchTableIndex:0,
				methodName:'',
				methodId:'',
				index:0,
				xindex:'',
				unitsList: [],
				produceManageTechList:[],
				facilityList:[],
				user_findByAll:[],
				tableData3:[],
				currentPage3:1,
				total3:0,
              processPlanId:'',
				      dialogTableVisible3:false
            }
        },
        mounted(){
			this.init()
			this.getuser_findByAll()
			this.getfacility()
        },
        methods:{
			handleSelectProductDetails11(index,row){
				this.finishedProductList[this.xindex].productImg = row.img
				this.finishedProductList[this.xindex].productId = row.id
				this.finishedProductList[this.xindex].title = row.title
				this.dialogTableVisible3 = false
			},
			handleCheck(){
				this.finishedProductList.pop()
			},
			// 成品列表添加
			addProduct(){
				var d = new Date();
				var curr_date = d.getDate();
				var curr_month = d.getMonth() + 1;
				var curr_year = d.getFullYear();
				String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
				String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
				var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;

				this.finishedProductList.push({
					technologyId:this.ruleForm.technologyId,
					technology:this.ruleForm.tename,
					productName:this.ruleForm.manageName,
					batch: yyyyMMdd + Math.ceil(Math.random()*10000),
					grade:'',
					totalNumber:'',
					surplusNumber:'',
					units:this.ruleForm.monad,
					productId:'',
					title:'',
					type:this.ruleForm.type
				})
			},
			handleCurrentChange3(val){
			    this.currentPage3 = val
			   this.getProductDetails()
			},
			// 获取关联产品介绍
			getProductDetails(){
				let data = {
					page:this.currentPage3
				}
				products_findByList(data).then((res)=>{
					this.tableData3 = res.rows
					this.total3 = res.total
				})
			},

			next(){
				if(this.active == 0){
					if(this.ruleForm.manageName == "" || this.ruleForm.manageName == null || this.ruleForm.manageName == undefined){
						this.$notify({
						    title: '提示',
						    message: '原料不能为空',
						    type: 'info',
						    duration:1000
						});
					}else{
						this.nextStep()
					}
				}

            },
			//下一步
			nextStep(){
				if (this.active++ > 0) {

				}
			},
			prev(){
               --this.active
               if(this.active<0)this.active = 0
			   this.finishedProductList = []

            },
			//获取 图片的 index
			handelsuccess(index){
				this.index = index
			},
			// 获取设备下拉
			getfacility(){
				facility_findByAll("").then((res)=>{
					 this.facilityList = res.data
				})
			},
			// 获取负责人下拉列表
			getuser_findByAll(){
				user_findByAll("").then((res)=>{
					this.user_findByAll = res.data
				})
			},
			imgPreview(file,fileList) {
				this.produceManageTechList[this.index].operaImg =  URL.createObjectURL(file.raw);
			    this.headImg =  URL.createObjectURL(file.raw);
			    let fileName = file.name;
			    let regex = /(.jpg|.gif|.png|.jpeg)$/;
			    if (regex.test(fileName.toLowerCase())) {
					this.produceManageTechList[this.index].files = file.raw
					this.produceManageTechList[this.index].operaImg = file.name
			    } else {
			        this.$message.error('请选择图片文件');
			    }

			},
			getfacilityDetails(ele){
				this.produceManageTechList[this.switchTableIndex].vieo = ele.name
				this.produceManageTechList[this.switchTableIndex].deviceId = ele.id
			},
			getuser(ele){
				this.produceManageTechList[this.switchTableIndex].principal = ele.name
				this.produceManageTechList[this.switchTableIndex].principalId = ele.id
			},
			// 判断开始时间和结束时间
			gettime() {
            	if (this.produceManageTechList[this.index].startTime != '' && this.produceManageTechList[this.index].endTime != '') {
                var oDate1 = new Date(this.produceManageTechList[this.index].startTime);
                var oDate2 = new Date(this.produceManageTechList[this.index].endTime);
                if (oDate1 > oDate2) {
                  this.$notify({
                    title: '提示',
                    message: '开始时间不得早于结束时间',
                    type: 'info'
                  });
                  this.produceManageTechList[this.index].startTime = '';
                  this.produceManageTechList[this.index].endTime = '';
                }
            	}
        	},
			// 切换工艺工序步骤
			switchTable(index){
				this.produceManageTechList[this.switchTableIndex+1].tech = this.technologies[index].processName
				// this.produceManageTechList[this.switchTableIndex+1].methodId = this.technologies[index].id
				this.switchTableIndex = index
				this.activeTechnologies = index
			},
			// 获取单位
			init() {
				unit_findByList("").then((res) => {
                  if (res.code == 200) {
                    this.unitsList = res.data;
                  }
             	});
			},
			// 选择成品
			handleSelect(index,row){
				this.ruleForm.manageName = row.tradeName
				this.ruleForm.type = row.type
				this.ruleForm.specification = row.specification
				this.ruleForm.predictYield = row.predict
				this.ruleForm.monad = row.predictSpec
				this.ruleForm.spec = row.spec
				this.ruleForm.technologyId = row.technologyId
				this.processPlanId = row.id

				this.dialogTableVisible = false
				scTechnology_selectId({id:row.technologyId}).then((res)=>{
					this.ruleForm.tename = res.data.processName
					this.ruleForm.tenum = res.data.approvalNumber
					this.ruleForm.tebz = res.data.standard
					if(!this.ruleForm.standardImg){
						this.ruleForm.img = this.$store.state.plantImg + this.ruleForm.standardImg
					}

					this.technologies = res.data.specification
					for(var i=0;i<this.technologies.length;i++){
						this.produceManageTechList.push({
							tech:'',
							startTime:'',
							endTime:'',
							deviceId:'',
							principalId:'',
							video:'',
							principal:'',
							operaImg:''
						})
					}
					this.produceManageTechList[0].tech = this.produceManageTechList[0].processName
					// this.technologyList[0].methodId = this.technologies[0].id
				})
			},
			// 选择 工艺工序添加到列表中
			handleSelectProductDetails(index,row){
				this.ruleForm.processName = row.processName
				this.ruleForm.approvalNumber = row.approvalNumber
				this.ruleForm.standard = row.standard
				this.ruleForm.biaozhunimages = this.$store.state.pathimg + row.standardImg
				this.ruleForm.technologyId = row.id
				this.dialogTableVisible1 = false
			},

			// 点击 添加品名打开弹窗
			addManure(){
				this.dialogTableVisible = true
				let data = {
					page:this.currentPage,
				}
				productionPlan_search(data).then((res) =>{
					this.materialList = res.data.content
					this.total = res.data.totalElements
				})
			},
			// 点击  添加工艺打开弹窗
			relevance(index,row){
				this.xindex = index
				this.dialogTableVisible3 = true
				this.getProductDetails()

			},
			//选择工艺工序弹窗列表的分页
			handleCurrentChange1(val){
			    this.currentPage1 = val
			},

			//选择品名弹窗列表的分页
            handleCurrentChange(val){
                this.currentPage = val
            },
			// 提交
            submitrule(){
				this.$confirm('确定要加工吗请谨慎操作', '提示', {
				    confirmButtonText: '确定',
				    cancelButtonText: '取消',
				    type: 'warning'
				}).then(() => {
					this.ruleForm.produceManageTechList = this.produceManageTechList
					this.ruleForm.processDetailList = this.finishedProductList
          for(var i=0;i<this.ruleForm.processDetailList.length;i++){
            this.ruleForm.processDetailList[i].processPlanId = this.processPlanId
          }

					let formdata = new FormData
					for(var i=0;i<this.ruleForm.produceManageTechList.length;i++){
					    if(this.ruleForm.produceManageTechList[i].files != "" && this.ruleForm.produceManageTechList[i].files != null){
					        formdata.append("files",this.ruleForm.produceManageTechList[i].files)
					    }
					}
					this.ruleForm.produceManageTechList =JSON.stringify(this.ruleForm.produceManageTechList)
					this.ruleForm.processDetailList = JSON.stringify(this.ruleForm.processDetailList)
					for(var a in this.ruleForm){
					    if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
					        this.ruleForm[a] = ""
					        formdata.append(a,'')
					    }else{
					        formdata.append(a,this.ruleForm[a])
					    }
					}
					productionManagement_save(formdata).then((res)=>{
							this.$notify({
						    title: '提示',
						    message: '收获成功',
						    type: 'success',
						    duration:1000
						});
						this.$router.go(-1)
					})
				})
            }
        }
    }
</script>

<style scoped>
    .el-pagination{
        text-align: center;
    }
	.addManure{
	    border-radius:8px;
	    margin-top:20px;
	    width:100%;
	    height:60px;
	    line-height:60px;
	    text-align: center;
	    font-size:16px;
	    background:#EBF5FF 100%;
	}
	.avatar-uploader .el-upload {
	   border: 1px dashed #d9d9d9;
	   border-radius: 6px;
	   cursor: pointer;
	   position: relative;
	   width:180px;
	   overflow: hidden;
	 }

	 .avatar-uploader .el-upload:hover {
	   border-color: #409EFF;
	 }

	 .avatar-uploader-icon {
	   font-size: 28px;
	   color: #8c939d;
	   width: 178px;
	   height: 178px;
	   line-height: 178px;
	   text-align: center;
	 }
	 .avatar {
	   width: 178px;
	   height: 178px;
	   display: block;
	 }
	 .addManure{
	     border-radius:8px;
	     margin-top:20px;
	     width:100%;
	     height:60px;
	     line-height:60px;
	     text-align: center;
	     font-size:16px;
	     background:#EBF5FF 100%;
	 }
</style>
